"""
---------------------------------------------------------------------
- File: init_db.py
- Date: 2025/11/6
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 数据库初始化
---------------------------------------------------------------------
"""

from select import select
from sqlmodel import SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession

# 数据库引擎
from app.db.session import async_engine
# 系统管理表模型
from app.models.ob1 import Glass
from app.models.system import Users, Roles
from app.schemas.enums import GenderEnum, UserStatusEnum, RoleStatusEnum


# 数据库初始化
async def init_db():
    # 1. 创建数据库表
    async with async_engine.begin() as conn:
        await conn.run_sync(SQLModel.metadata.create_all)
    # 2. 数据库初始化数据（仅当表为空时）
    async with AsyncSession(async_engine) as session:
        async with session.begin():
            # 判断空表才插入，避免重复
            glass_result = await session.exec(select(Glass).limit(1))
            users_result = await session.exec(select(Users).limit(1))
            roles_result = await session.exec(select(Roles).limit(1))
            if glass_result.first() is None:
                # 插入数据
                glasses = [
                    Glass(name="1班", description="python学习班1"),
                    Glass(name="2班", description="python学习班2"),
                    Glass(name="3班", description="python学习班3"),
                    Glass(name="4班", description="python学习班4"),
                    Glass(name="5班", description="python学习班5"),
                    Glass(name="6班", description="python学习班6"),
                    Glass(name="7班", description="python学习班7"),
                    Glass(name="8班", description="python学习班8"),
                    Glass(name="9班", description="python学习班9"),
                ]
                session.add_all(glasses)
                await session.commit()
            if users_result.first() is None:
                # 插入数据
                admin_user = Users(
                    user_no="admin",
                    hash_password="$argon2id$v=19$m=65536,t=3,p=4$m1dI3jkRhY52D70U8Be8Zw$IIFcrcG0YD1bLjogNytSBUFcoorZHZvzuYTKn2EvPl0",
                    user_name="管理员",
                    nick_name="系统操作管理员",
                    user_gender=GenderEnum.MALE.value,
                    user_email="xxzjyzd@126.com",
                    user_phone="17385308520",
                    status=UserStatusEnum.ACTIVE.value,
                    last_login=None,
                )
                role = Roles(
                    role_no="admin",
                    role_name="管理员",
                    role_desc="系统操作管理员",
                    status=RoleStatusEnum.ACTIVE.value,
                    users=[admin_user],
                )
                session.add(admin_user)
                session.add(role)
                await session.commit()
